package br.com.db;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import com.dropbox.core.DbxClient;
import com.dropbox.core.DbxDelta;
import com.dropbox.core.DbxDelta.Entry;
import com.dropbox.core.DbxEntry;
import com.dropbox.core.DbxException;
import com.dropbox.core.DbxRequestConfig;

public class DBDeltaTester {

	private static final String ACCESS_TOKEN = "cXJce5YrLLkAAAAAAAAAARou5oTnTRdvR-FuRtkKGU1jgyUT61v122y2KmQrxLW9";
	private static final String CURSOR_PATH_LINUX = "/home/talespf/cursor.txt";
	private static final String CURSOR_PATH_WINDOWS = "C:\\Users\\talespf\\cursor.txt";
	private DbxRequestConfig config;
	private Timer timer;

	public DBDeltaTester(int seconds) {
		config = new DbxRequestConfig("JavaTutorial/1.0", Locale.getDefault()
				.toString());

		timer = new Timer();
		timer.scheduleAtFixedRate(new DBTask(), 0, seconds * 1000);
	}

	class DBTask extends TimerTask {

		public void run() {

			// obter novas entries no DB
			List<Entry<DbxEntry>> newEntries = getNewEntries();

			// se nao ha novas entries, nao se faz nada
			if (newEntries.isEmpty()) {
				System.out.println("No new entries.");
			} else {

				// inicia thread pool para processar novas entries
				ExecutorService executor = Executors.newFixedThreadPool(5);

				for (Entry<DbxEntry> entry : newEntries) {

					Runnable worker = new WorkerThread(new DbxClient(config, ACCESS_TOKEN), entry);
					executor.execute(worker);

					// while (!executor.isTerminated()) {
					// }
					//
					// System.out.println("Finished all threads");
				}
				executor.shutdown();
			}
		}

		private List<Entry<DbxEntry>> getNewEntries() {

			String dbxCursor;
			List<Entry<DbxEntry>> entries = null;
			DbxDelta<DbxEntry> dbxDelta;
			DbxClient dbxClient = new DbxClient(config, ACCESS_TOKEN);

			try {
				// ler arquivo para obter cursor
				dbxCursor = readCursor();

				dbxDelta = dbxClient.getDelta(dbxCursor);
				entries = dbxDelta.entries;
				String newCursor = dbxDelta.cursor;
				// System.out.println(newCursor);

				while (dbxDelta.hasMore) {
					dbxDelta = dbxClient.getDelta(newCursor);
					entries.addAll(dbxDelta.entries);
					newCursor = dbxDelta.cursor;
					// System.out.println(newCursor);
				}

				// salvar novo cursor
				saveCursor(newCursor);
				System.out.println("Last read droppox cursor: " + newCursor);

			} catch (IOException e) {
				e.printStackTrace();
			} catch (DbxException e) {
				e.printStackTrace();
			}

			return entries;
		}

		private void saveCursor(String newCursor) throws IOException {

			String path = System.getProperty("os.name").equalsIgnoreCase("Linux") ? CURSOR_PATH_LINUX : CURSOR_PATH_WINDOWS;

			File file = new File(path);
			file.delete();

			FileWriter fileWriter = new FileWriter(new File(path));
			fileWriter.write(newCursor);
			fileWriter.close();
		}

		private String readCursor() throws IOException {
			
			String path = System.getProperty("os.name").equalsIgnoreCase("Linux") ? CURSOR_PATH_LINUX : CURSOR_PATH_WINDOWS;

			File file = new File(path);
			String result = null;

			if (!file.exists()) {
				file.createNewFile();
			} else {
				BufferedReader reader = new BufferedReader(new FileReader(file));
				String line = null;
				while ((line = reader.readLine()) != null) {
					result = line;
				}
				reader.close();
			}
			return result;
		}
	}

	/**
	 * @param args
	 * @throws DbxException
	 */
	public static void main(String[] args) throws DbxException {

		new DBDeltaTester(20);
	}

}
